package OJPractice;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

class MyThreadPool {
    // 阻塞队列用来存放任务
    private BlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();
    // 入队列操作的方法
    // 就是让这个线程池中不停的入队元素，然后执行任务
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
    // 此处实现一个固定线程数的线程池
    // 线程池就像消费者一样不停的去任务然后去执行
    public MyThreadPool(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
               while (true) {
                   try {
                       Runnable runnable = queue.take();
                       runnable.run();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
            });
            t.start();
        }
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            int num = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello " + num);
                }
            });
        }
    }
}
